/*
Copyright 2010,2011 Matt Van Der Westhuizen

This file is part of CGLL.

CGLL is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

CGLL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with CGLL.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.chaoticengine.cgll.entity.component.tween;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * This tween is used to combine a number of different tweens into a complex
 * animation.
 *
 * @author Matt Van Der Westhuizen <mattpwest@gmail.com>
 */
public class ComplexAnimationTween extends Tween {
    protected int maxState = -1;
    protected int state = -1;
    protected HashMap<Integer, ArrayList<Tween>> tweens = new HashMap<Integer, ArrayList<Tween>>();

    public ComplexAnimationTween() {
        super(0);
    }

    public void addTween(int state, Tween tween) {
        if (tween == null) {
            throw new NullPointerException("Argument 'tween' may not be null.");
        }

        if (!tween.getRepeatMode().equals(Tween.RepeatMode.None)) {
            throw new IllegalArgumentException("Only non-repeating tweens can be used in an animation.");
        }

        if (!tweens.containsKey(state)) {
            tweens.put(state, new ArrayList<Tween>());
        }

        if (state > maxState) {
            maxState = state;
        }

        tweens.get(state).add(tween);

        duration += tween.getDuration();
    }

    @Override
    public void doUpdate(int delta) {
        // Beginning state
        if (state < 0) {
            state = 0;

            TweenComponent tc = getOwner();
            for (Tween t : tweens.get(state)) {
                tc.addTween(t);
            }

            return;
        }

        // Check for next state
        if (state <= maxState) {
            boolean complete = true;
            TweenComponent tc = getOwner();

            for (Tween t : tweens.get(state)) {
                complete = complete && t.isDone();
            }

            if (complete) {
                // Remove old tweens
                for (Tween t : tweens.get(state)) {
                    t.doUpdate(delta);
                    tc.removeTween(t);
                }

                // Next state
                state++;

                if (state <= maxState) {
                    for (Tween t : tweens.get(state)) {
                        tc.addTween(t);
                    }
                }
            }
        }
    }

    @Override
    public boolean isDone() {
        return(state > maxState);
    }
}